#include <iostream>
#include <limits>

#include "Human.h"

using namespace std;

Move* Human::play()
{
  //This is a loop so we can jump to the start if the user cancels.
  while(true)
  {
    char col, row;
    static Move* moves = NULL;
    if(moves)
      position->freeMoves(moves);
    /*
    int size = position->getMoves(moves);
    for(int i = 0; i < size; i++)
    {
      cout << i << " ";
      cout << (char)('A' + moves[i].fromCol()) << (char)('8' - moves[i].fromRow()) << '-';
      cout << (char)('A' + moves[i].toCol()) << (char)('8' - moves[i].toRow()) << endl;
    }
    int answer = -1;
    while(answer < 0 || answer >= size)
    {
      cout << "Enter thine move, peasant!" << endl;
      cin >> answer;
      if (!cin.good())
      {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        answer = -1;
        cout << "Wrong answer!" << endl;
      }
    }
  
    return moves+answer; //TODO: Make this not a horrible thing
    */
    
    cout << endl;
    cout << "Enter thine piece, knave!" << endl;
    
    cin >> col >> row;
    if('A' <= col && col <= 'H')
    col -= 'A';
    else
      col -= 'a';
    row = '8' - row;
    
    int matches = 0;
    int size = position->getMoves(moves);
    
    cout << " 0 Cancel" << endl;
    for(int i = 0; i < size; i++)
    {
      if(moves[i].fromCol() == col && moves[i].fromRow() == row)
      {
        matches++;
        cout << matches << " ";
        cout << (char)('A' + moves[i].toCol()) << (char)('8' - moves[i].toRow()) << endl;
      }
    }
    
    int answer = -1;
    while(answer < 0 || answer > matches)
    {
      cout << "Enter thine move, peasant!" << endl;
      cin >> answer;
      if (!cin.good())
      {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        answer = -1;
        cout << "Wrong answer!" << endl;
      }
    }
    
    if(answer == 0) continue;
    
    for(int i = 0; i < size; i++)
    {
      if(moves[i].fromCol() == col && moves[i].fromRow() == row)
      {
        answer--;
        if(!answer) return moves+i;
      }
    }
    
    return NULL; //If that loop gets here it means it counted more when adding up the moves than when subtracting and something is wrong; I give up.
  }
}

Human::Human() : AI()
{}
